package org.me.marble;

import android.os.*;
import android.app.*;

import android.view.KeyEvent;
import android.view.MotionEvent;
import android.graphics.PixelFormat;
import android.hardware.SensorEvent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;

/**
 *
 * @author tungi
 */

public class GameActivity extends Activity implements Runnable,
        MySensorEventListener,DialogInterface.OnClickListener{
    public static GameActivity game;//for getResources() method calls
    
    private GameView _gameview;
    private MySensorEvent listener;
    private GameRenderer _renderer;
    private LoadingView loadingview;

    private long last_time=0;
    private boolean initialized=false,fullGame=false;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle){try{
        super.onCreate(icicle);

        game=this;

        getWindow().setFormat(PixelFormat.RGBA_8888);

        if(OptionsLibrary.tilt_control){
        	try{
            	listener=MySensorEvent.register(this,this);
        	}catch(Exception e){}
            if(listener==null){
                OptionsLibrary.tilt_control=false;
                new AlertDialog.Builder(this)
                    .setTitle("Error!")
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setMessage("Cannot iniatilize the orientation sensor!")
                    .setPositiveButton("OK",this)
                    .show();
            }
        }       
        
        if(OptionsLibrary.current_level==1)
        	fullGame=true;
        
        loadingview=new LoadingView(this);
        loadingview.show();   
        /*END*/

        //this need, that onCreate, onStart, onResume run down,
        //and the contentview changes to loadingView
        //then we can load the game contents
        new Handler().postDelayed(this,500);
        }catch(Exception e){}
    }

    @Override
    protected void onPause(){
        if(_renderer!=null)
            _renderer.setPause(true);
		if(listener!=null)
	            listener.unregister();
		super.onPause();
    }
    
    @Override
    protected void onDestroy(){
    	super.onDestroy();
    }

    ////////////////////////////////////////////////////////////////////////////

    @Override
    public boolean onKeyDown(int keyCode,KeyEvent event){
        if(keyCode==OptionsLibrary.left_key && !OptionsLibrary.tilt_control
        		&& !OptionsLibrary.onscreen && !_renderer.isPause()){
            _renderer.rotateDirection(Math.PI*OptionsLibrary.key_sensitivity/180f);
            return true;
        }
        else if(keyCode==OptionsLibrary.right_key && !OptionsLibrary.tilt_control
        		&& !OptionsLibrary.onscreen && !_renderer.isPause()){
            _renderer.rotateDirection(-Math.PI*OptionsLibrary.key_sensitivity/180f);
            return true;
        }
        else if(keyCode==KeyEvent.KEYCODE_BACK){
        	_renderer.exit();
            finish();
            return true;
        }
        else
            return true;//super.onKeyDown(keyCode,event);
    }
    
    @Override
    public boolean onTrackballEvent(MotionEvent event){
    	if(!OptionsLibrary.tilt_control && !OptionsLibrary.onscreen && !_renderer.isPause()){
    		_renderer.rotateDirection(Math.PI*OptionsLibrary.key_sensitivity*event.getX()/180f);
    		return true;
    	}
    	return false;
    }

    public void onSensorChanged(SensorEvent event){
        if(_renderer==null || _renderer.isPause())
            return;
        //if (event.sensor.getType()==SensorManager.SENSOR_ORIENTATION){
            if((System.currentTimeMillis()-last_time)>=100){
                last_time=System.currentTimeMillis();
                double delta=(event.values[1]-OptionsLibrary.tilt_orientation)*
                        OptionsLibrary.tilt_sensitivity*Math.PI/180f/90f;
                _renderer.rotateDirection(delta);
            }
        //}
    }

    public void onClick(DialogInterface arg0,int arg1){
        arg0.dismiss();
        finish();
    }

    public void run(){
        _gameview=new GameView(this);
    }

    ////////////////////////////////////////////////////////////////////////////

    public GameView getGameView(){
        return _gameview;
    }

    public boolean isLevelInitialized(){
        return initialized;
    }

    public void setRenderer(GameRenderer _renderer){
        this._renderer=_renderer;
    }

    public void levelInitialized(){
        initialized=true;
        if(loadingview.isFired())
            //setContentView(_gameview);
            _gameview.setContentView();
    }
    
    public void saveCurrentLevelScore(boolean end){
    	SharedPreferences sd=getSharedPreferences(
				Context.ACTIVITY_SERVICE,Context.MODE_PRIVATE);
    	SharedPreferences.Editor ed=getSharedPreferences(
    			Context.ACTIVITY_SERVICE,Context.MODE_PRIVATE).edit();
    	if(OptionsLibrary.game_type.equals("normal")){    		
    		int old=sd.getInt("level"+
    				Integer.toString(OptionsLibrary.current_level)+"_normal",0);
    		if((int)_renderer.getPoints()>old)
    			ed.putInt("level"+Integer.toString(OptionsLibrary.current_level)+
    					"_normal",(int)_renderer.getPoints());
    	}
    	else if(OptionsLibrary.game_type.equals("point")){
    		int old=sd.getInt("level"+
    				Integer.toString(OptionsLibrary.current_level)+"_point",0);
    		if((int)_renderer.getPoints()>old)
    			ed.putInt("level"+Integer.toString(OptionsLibrary.current_level)+
    					"_point",(int)_renderer.getPoints());
		}
    	else if(OptionsLibrary.game_type.equals("time") && end){
    		float old=sd.getFloat("level"+
    				Integer.toString(OptionsLibrary.current_level)+"_time",0.0f);
    		if(_renderer.getPoints()>old)
    			ed.putFloat("level"+Integer.toString(OptionsLibrary.current_level)+
    					"_time",MyMath.makeRound(_renderer.getPoints(),3));
		}
    	ed.commit();
    }

    public void endLevel(boolean loadnext){ 
    	if(OptionsLibrary.lifes>0 && !loadnext){
    		_renderer.reset();
    		return;
    	}

    	_renderer.exit();
        OptionsLibrary.points+=_renderer.getPoints();
        
        saveCurrentLevelScore(loadnext);
        
        //we reach the end of the path
        if(!loadnext){
            showHighScore(false);
        }
        else{
            int next_level=getResources().getIdentifier("level"+
                    Integer.toString(OptionsLibrary.current_level+1),"xml",getPackageName());
            if(next_level!=0){
                initialized=false;
                loadingview.deleteFireState();
                if(OptionsLibrary.current_level==OptionsLibrary.reached_level)
                    OptionsLibrary.reached_level++;
                OptionsLibrary.current_level++;
                //setContentView(new GameView(this));
                loadingview.show();
                new Handler().postDelayed(this,500);
            }
            else{
                showHighScore(true);
            }
        }
    }

    public void showHighScore(boolean finish){        
    	float point=0.0f;
        if(OptionsLibrary.game_type.equals("normal"))
        	point=OptionsLibrary.bestNormal;
        else if(OptionsLibrary.game_type.equals("point"))
        	point=OptionsLibrary.bestPoint;
        else if(OptionsLibrary.game_type.equals("time"))
        	point=OptionsLibrary.bestTime;
        
        if(OptionsLibrary.points>point && !OptionsLibrary.game_type.equals("time"))
            new HighScoreView().showNewHighScore();
        else if(OptionsLibrary.points<point && finish && fullGame &&
        		OptionsLibrary.game_type.equals("time"))
        	new HighScoreView().showNewHighScore();
        else
            new HighScoreView().showEndGame();
    }
}
